<template>
    <el-container style="height: 100vh; border: 1px solid #eee">
        <el-aside width="15%" style="background-color: rgb(238, 241, 246)">
            <div
                style="padding: 10px; background-color: rgb(238, 241, 246); color: #333; text-align: left; display: flex; flex-direction: column; margin-bottom: 10px;">
                <el-row style="margin-top: 20px;">
                    <el-col :span="24">
                        <div class="grid-content bg-purple-dark" style="left: auto; display: flex; align-items: center;">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                class="bi bi-rss" viewBox="0 0 16 16">
                                <path
                                    d="M14 1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h12zM2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2z" />
                                <path
                                    d="M5.5 12a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0zm-3-8.5a1 1 0 0 1 1-1c5.523 0 10 4.477 10 10a1 1 0 1 1-2 0 8 8 0 0 0-8-8 1 1 0 0 1-1-1zm0 4a1 1 0 0 1 1-1 6 6 0 0 1 6 6 1 1 0 1 1-2 0 4 4 0 0 0-4-4 1 1 0 0 1-1-1z" />
                            </svg> <strong style="flex-grow: 1;font-size: 24px;">RSS-Reader</strong>
                        </div>
                    </el-col>
                </el-row>
            </div>
            <div
                style="padding: 10px; background-color: rgb(238, 241, 246); color: #333; text-align: left; display: flex; align-items: center;">
                <strong style="flex-grow: 1;font-size: 18px;">订阅源</strong>
                <el-button type="text" icon="el-icon-search" @click="leftDialogVisible = true"
                    style="margin-left: 5px;font-size: 20px;" circle></el-button>
                <el-button type="text" icon="el-icon-circle-plus-outline" @click="centerDialogVisible = true"
                    style="margin-right: 20px;font-size: 20px;"></el-button>
                <el-popover placement="top" width="50px" style="font-size: 20px;" v-model="visible">
                    <el-row>
                        <el-col style="margin-bottom: 5px; display: flex;justify-content: center;align-items: center;">
                            <el-button type="primary" @click="category_manage">分类管理</el-button></el-col>
                        <el-col style="margin-bottom: 5px; display: flex;justify-content: center;align-items: center;">
                            <el-button type="primary" @click="inducts">导入...</el-button></el-col>
                        <el-col style="margin-bottom: 5px; display: flex;justify-content: center;align-items: center;">
                            <el-button type="primary" @click="deduced">导出...</el-button></el-col>

                    </el-row>
                    <el-button slot="reference" type="text" icon="el-icon-more-outline"
                        style="font-size: 20px;"></el-button>
                </el-popover>
            </div>
            <el-menu :default-openeds="defaultOpeneds" :router="true">
                <el-submenu v-for="category in categories" :key="category.id" :index="category.id.toString()">
                    <template slot="title"><strong>{{ category.chname }}</strong></template>
                    <el-menu-item-group>
                        <el-menu-item v-for="item in category.items" :key="item.id"
                            :index="'/article/' + item.id.toString()">{{
                                item.title }}
                            <time class="time">{{ item.item_count }} </time>
                        </el-menu-item>
                    </el-menu-item-group>
                </el-submenu>
            </el-menu>
        </el-aside>
        <router-view></router-view>
        <el-dialog title="添加订阅" :visible.sync="centerDialogVisible" width="30%" center>
            <el-input placeholder="输入RSS源" v-model="input" @keyup.enter.native="search" class="input_style">
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
            <!-- <el-empty v-if="!showIframe" description="暂无信息"></el-empty> -->
            <el-skeleton v-if="!showIframe" :rows="6" animated />
            <el-card v-else class="card-item">
                <div slot="header" class="card-header">
                    <strong class="card-title">{{ this.Rss.title }}</strong>
                </div>
                <div class="card-info">
                    <time class="time">{{ this.Rss.description }}</time>
                    <div class="card-description"><a :href="this.Rss.link" target="_blank">{{ this.Rss.link }}</a></div>
                </div>
                <el-button type="primary" round @click="add">订阅</el-button>
            </el-card>
            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="搜索文章" :visible.sync="leftDialogVisible" width="80%" center>
            <el-input placeholder="搜索文章" v-model="finding" @keyup.enter.native="find" class="input_style">
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
            <el-empty v-if="!showIframe" description="暂无信息"></el-empty>
            <el-card v-else style="width: 100%;height: 100%;">
                <el-table :data="tableData" style="width: 100%" height="250" @row-click="clickRow">
                    <el-table-column fixed prop="title" label="标题" width="150">
                    </el-table-column>
                    <el-table-column prop="description" label="描述" width="120">
                    </el-table-column>
                    <el-table-column prop="publishedAt" label="发表时间" width="120">
                    </el-table-column>
                    <el-table-column prop="link" label="链接">
                    </el-table-column>
                </el-table>
            </el-card>
            <span slot="footer" class="dialog-footer">
                <el-button @click="leftDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="leftDialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog :visible.sync="dialogVisible" title="上传文件" width="400px">
            <el-upload class="upload-demo" action :http-request="uploadFile" ref="upload" :limit="fileLimit"
                :on-remove="handleRemove" :file-list="fileList" :on-exceed="handleExceed" :before-upload="beforeUpload"
                :show-file-list="false" :headers="headers">
                <el-button class="btn"><i class="el-icon-paperclip"></i>上传附件</el-button>
            </el-upload>
        </el-dialog>

        <el-dialog :visible.sync="Visible" title="新文章内容" width="600px">
            <el-table :data="[newArticle]" style="width: 100%">
                <el-table-column prop="title" label="标题"></el-table-column>
                <el-table-column prop="description" label="描述"></el-table-column>
                <!-- 其他文章属性列 -->
            </el-table>
        </el-dialog>
    </el-container>
</template>

<script>
import axios from 'axios';
import { io } from 'socket.io-client';
export default {
    data() {
        return {
            categories: [],
            articles: [],
            iframeSrc: '',
            currentRoute: this.$route.path,
            centerDialogVisible: false,
            leftDialogVisible: false,
            input: '',
            finding: '',
            showIframe: false,
            Rss: '',
            tableData: [],
            articleTable: [],
            visible: false,
            dialogVisible: false,
            Visible: false,
            newArticleData: [], // 新文章数据
            newArticles: {},
            rss_title: '',
            category_chname: '',
            uploadUrl: 'http://localhost:5000/import-opml',
            fileList: [],
            // 允许的文件类型
            fileType: ["pdf", "doc", "docx", "xls", "xlsx", "txt", "png", "jpg", "bmp", "jpeg", "opml"],
            // 运行上传文件大小，单位 M
            fileSize: 50,
            // 附件数量限制
            fileLimit: 1,
            //请求头
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        };
    },

    computed: {
        defaultOpeneds() {
            return this.categories.map(category => category.id.toString());
        },
    },

    created() {
        this.showIframe = false
        this.fetchCategories();
        this.fetchArticles();
    },
    mounted() {
        const socket = io('http://localhost:5000');
        console.log("正在监听")

        // 监听服务器发送的 new_articles 事件
        socket.on('new_articles', (data) => {
            // 获取新文章数据
            this.newArticleData.push(data);
            const newArticles = data.articles;
            console.log(this.newArticles)
            // 更新新文章数据
            if (newArticles.length > 0) {
                this.newArticles = newArticles[0];
                this.rss_title = this.newArticles.rss_title
                this.category_chname = this.newArticles.chname
                // this.Visible = true;
                this.showNotification()
            }
        });
    },

    methods: {
        showArticle() {
            this.Visible = true;
        },
        showNotification() {
            this.$notify({
                title: this.category_chname + "：" + this.rss_title,
                message: JSON.stringify(this.newArticles.title), // 使用 JSON.stringify 将数组转换为字符串
                // offset: 100
                duration: 0
            });
        },
        clickRow(row) {
            window.open(row.link, '_blank')
        },
        beforeUpload(file) {
            if (file.type != "" && file.type != null && file.type != undefined) {
                //截取文件的后缀，判断文件类型
                const FileExt = file.name.replace(/.+\./, "").toLowerCase();
                //计算文件的大小
                const isLt5M = file.size / 1024 / 1024 < 50; //这里做文件大小限制
                //如果大于50M
                if (!isLt5M) {
                    this.$showMessage('上传文件大小不能超过 50MB!');
                    return false;
                }
                //如果文件类型不在允许上传的范围内
                if (this.fileType.includes(FileExt)) {
                    return true;
                }
                else {
                    this.$message.error("上传文件格式不正确!");
                    return false;
                }
            }
        },
        //上传了的文件给移除的事件，由于我没有用到默认的展示，所以没有用到
        handleRemove() {
        },
        //这是我自定义的移除事件
        handleClose(i) {
            this.fileList.splice(i, 1);//删除上传的文件
            if (this.fileList.length == 0) {//如果删完了
                this.fileflag = true;//显示url必填的标识
                this.$set(this.rules.url, 0, { required: true, validator: this.validatorUrl, trigger: 'blur' })//然后动态的添加本地方法的校验规则
            }
        },
        //超出文件个数的回调
        handleExceed() {
            this.$message({
                type: 'warning',
                message: '超出最大上传文件数量的限制！'
            }); return
        },
        //上传文件的事件
        uploadFile(item) {
            // this.$showMessage('文件上传中........')
            //上传文件的需要formdata类型;所以要转
            let FormDatas = new FormData()
            FormDatas.append('file', item.file);
            axios({
                method: 'post',
                url: 'http://localhost:5000/import-opml',
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
                timeout: 30000,
                data: FormDatas
            }).then(res => {
                if (res.data.id != '' || res.data.id != null) {
                    this.fileList.push(item.file);//成功过后手动将文件添加到展示列表里
                    let i = this.fileList.indexOf(item.file)
                    this.fileList[i].id = res.data.id;//id也添加进去，最后整个大表单提交的时候需要的
                    if (this.fileList.length > 0) {//如果上传了附件就把校验规则给干掉
                        this.fileflag = false;
                        // this.$set(this.rules.url, 0, '')
                    }
                    this.handleSuccess();
                }
            }).catch(error => {
                console.error(error);
            });
        },
        //上传成功后的回调
        handleSuccess() {
            this.$message({
                type: 'success',
                message: '导入成功！'
            });
            this.fetchCategories()
        },
        fetchCategories() {
            axios
                .get('http://localhost:5000/get-categories')
                .then(response => {
                    console.log(response)
                    this.categories = response.data;
                })
                .catch(error => {
                    console.error(error);
                });
        },
        search() {
            console.log(`searchInput 输入框点击了回车键，当前输入内容：${this.input}`);
            this.addRSS()
        },
        category_manage() { },
        fetchArticles() {
            axios
                .get('http://localhost:5000/get-articles')
                .then(response => {
                    this.articles = response.data;
                })
                .catch(error => {
                    console.error(error);
                });
        },
        addRSS() {
            const url = this.input
            axios.post('http://localhost:5000/check-rss', { url })
                .then(response => {
                    // 处理后端返回的响应
                    const data = response.data;
                    if (data.isValid) {
                        // 是RSS源，可以使用data中的其他相关信息进行操作
                        console.log('这是一个有效的RSS源');
                        this.$message({
                            type: 'success',
                            message: '这是一个有效的RSS源！'
                        });
                        console.log('RSS信息:', data.rssInfo);
                        this.Rss = data.rssInfo
                        this.showIframe = true
                    } else {
                        // 不是RSS源
                        console.log('这不是一个有效的RSS源');
                        this.$message({
                            type: 'error',
                            message: '这不是一个有效的RSS源！'
                        });
                    }
                })
                .catch(error => {
                    console.error('发生错误：', error);
                });
            window.location.reload()
        },
        inducts() {
            this.dialogVisible = true;
        },
        deduced() {
            axios.get('http://localhost:5000/export-opml')
                .then(response => {
                    const data = response.data;
                    const url = window.URL.createObjectURL(new Blob([data]));
                    const link = document.createElement('a');
                    link.href = url;
                    link.setAttribute('download', 'rss_sources.opml');
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    window.URL.revokeObjectURL(url);
                })
                .catch(error => {
                    console.error(error);
                });
        },
        add() {
            // 调用后端接口添加订阅
            const data = {
                title: this.Rss.title,
                description: this.Rss.description,
                url: this.Rss.link
            };
            axios.post('http://localhost:5000/add-rss-source', data)
                .then(response => {
                    // 添加成功后的处理逻辑
                    console.log('RSS source added successfully');
                    this.$message({
                        type: 'success',
                        message: '添加成功！'
                    });
                    console.log(response)
                })
                .catch(error => {
                    // 添加失败后的处理逻辑
                    console.error('Failed to add RSS source:', error);
                });
        },
        find() {
            axios.post('http://localhost:5000/search-articles', { search_text: this.finding })
                .then(response => {
                    this.tableData = response.data.table_data;
                    this.showIframe = true
                })
                .catch(error => {
                    console.error(error);
                });
        }
    },
};
</script>

<style>
.input_style {
    margin-bottom: 10px;
}

.el-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    border: 1px solid #eee;
}

.el-aside {
    flex-shrink: 0;
    background-color: rgb(238, 241, 246);
    color: #333;
}

.card-item {
    width: 400px;
    margin-bottom: 10px;
    border-radius: 10px;
    /* 添加圆角样式 */
    transition: box-shadow 0.3s;
    /* 添加过渡效果 */
}

.custom-main {
    flex-grow: 1;
    /* 占据剩余空间 */
    width: 85%;
    /* 设置自定义宽度值 */
    margin: 0 auto;
    /* 水平居中对齐 */
}

.empty-state {
    /* display: flex;
  align-items: center;
  justify-content: center; */
    margin: 0 auto;
    width: 55%;
}

.card-header {
    display: flex;
    align-items: center;
}

.card-title {
    font-size: 18px;
    font-weight: bold;
    margin-left: 10px;
}

.card-info {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.time {
    margin-right: 10px;
}

.card-description {
    text-align: left;
}

.time {
    font-size: 13px;
    text-align: right;
    color: #999;
}
</style>
